﻿using System;
using System.Xml;
using Geckon.Octopus.Controller.Interface;
using Geckon.Octopus.Data;

namespace Geckon.Octopus.Controller.Service
{
    // NOTE: If you change the class name "ControllerService" here, you must also update the reference to "ControllerService" in App.config.
    public class ControllerService : IControllerService
    {
        public string GetSession( int clientID )
        {
            throw new NotImplementedException();
        }

        public void AddJob( string jobXml )
        {
            // TODO: Validate jobXml

            // TODO: Add to database if valid
            try
            {
                XmlDocument xml = new XmlDocument();

                xml.LoadXml( jobXml );

                using( DatabaseDataContext db = new DatabaseDataContext() )
                {
                    db.Job_Insert( int.Parse( xml.DocumentElement.Attributes["ClientID"].InnerText ), 0, jobXml );
                }
            }
            catch (Exception)
            {
                
                throw;
            }
        }

        public string GetJobs()
        {
            try
            {
                XmlDocument xml = new XmlDocument();

                xml.LoadXml( "<ICollection></ICollection>" );

                using( DatabaseDataContext db = new DatabaseDataContext() )
                {
                    foreach( Job job in db.Job_GetBy( null, null, null, null, null, true ) )
                    {
                        XmlDocument jobXml = new XmlDocument();

                        jobXml.LoadXml( job.JobXML );

                        xml.DocumentElement.AppendChild( xml.ImportNode( jobXml.DocumentElement, true ) );
                    }
                }

                return xml.OuterXml;
            }
            catch (Exception e)
            {
                // TODO: Implement proper error handling
                return e.Message;
                throw;
            }
        }

        public string GetJobByID(int id)
        {
            throw new NotImplementedException();
        }

        public string GetJobByStatus(int status)
        {
            throw new NotImplementedException();
        }


    }
}